package net.wanho.shop.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import net.wanho.shop.entity.SysFile;
import net.wanho.shop.mapper.FileMapper;
import net.wanho.shop.service.FileService;
import net.wanho.shop.vo.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Author：汤小洋
 * Date：2025-09-19 16:27
 * Description：<描述>
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class FileServiceImpl implements FileService {

    private final FileMapper fileMapper;

    private String FILE_UPLOAD_PATH = System.getProperty("user.dir") + File.separator + "springboot-shop" + File.separator + "files" + File.separator;

    @Override
    public Page<SysFile> findByPage(int pageNum, int pageSize, SysFile sysFile) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysFile> users = fileMapper.selectParams(sysFile);
        PageInfo<SysFile> pageInfo = new PageInfo<>(users);

        return new Page<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        String fileUUID = IdUtil.fastSimpleUUID() + "." + type;
        String url = "http://localhost:7777/file/" + fileUUID;
        String md5 = SecureUtil.md5(file.getInputStream());

        System.out.println(FILE_UPLOAD_PATH);
        File uploadFile = new File(FILE_UPLOAD_PATH + fileUUID);

        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }



        SysFile sysFile = new SysFile();
        sysFile.setName(originalFilename);
        sysFile.setType(type);
        sysFile.setSize(size);
        sysFile.setUrl(url);
        sysFile.setMd5(md5);
        fileMapper.insert(sysFile);

        return url;
    }

    @Override
    public byte[] getFile(String fileUUID) {
        File file = new File(FILE_UPLOAD_PATH + fileUUID);
        byte[] bytes = FileUtil.readBytes(file);
        return bytes;
    }
}
